//
//  YAYIDateController.m
//  YAYIDoctor
//
//  Created by hxp on 16/5/18.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIDateController.h"

#import "YAYIDateCell.h"
#import "YAYIDateModel.h"
#import "YAYISchededdModel.h"
#import "YAYISchedulingItemModel.h"

@interface YAYIDateController ()<UITableViewDelegate,UITableViewDataSource, YAYIDateControllerDelegate>

@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataAry;


@property (nonatomic,strong)NSMutableArray *sectionArray;
@property (nonatomic,strong)NSMutableArray *monthParamArray;

@property (nonatomic, assign) NSInteger startTimeStamp;

/**
 *  保存当前点击的位置
 */
@property (nonatomic, strong) NSIndexPath *oldIndexPath;
@property (nonatomic, assign) NSInteger oldIndex;

@end

@implementation YAYIDateController


- (NSMutableArray *)sectionArray
{
    if (nil == _sectionArray) {
        _sectionArray = [NSMutableArray array];
        
        // 上个月第一天星期几
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYY-MM-01";
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        formatter.dateFormat = @"YYYY-MM-dd";
        NSDate *firstDayDate = [formatter dateFromString:dateStr];
        
        NSInteger thisMonthStamp = [firstDayDate timeIntervalSince1970];
        NSInteger lastMonthStamp = thisMonthStamp - 24 * 60 * 60;
        NSInteger nextMonthStamp = thisMonthStamp + 24 * 60 * 60 * 35;
        
        formatter.dateFormat = @"YYYY";
        NSArray *yearStr = @[[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:lastMonthStamp]],
                             [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:thisMonthStamp]],
                             [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:nextMonthStamp]]];
        
        formatter.dateFormat = @"MM";
        NSArray *monthStr = @[[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:lastMonthStamp]],
                              [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:thisMonthStamp]],
                              [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:nextMonthStamp]]];
        
        // 上月第一天周几
        NSInteger lastMonthFirstDayWeek = [self firstWeekdayInThisMonth:[NSDate dateWithTimeIntervalSince1970:lastMonthStamp]];
        if (lastMonthFirstDayWeek == 0) {
            lastMonthFirstDayWeek = 6;
        }
        // 上月天数, 本月天数， 下月天数
        NSInteger lastMonthDays = [self totaldaysInThisMonth:[NSDate dateWithTimeIntervalSince1970:lastMonthStamp]];
        NSInteger thisMonthDays = [self totaldaysInThisMonth:firstDayDate];
        NSInteger nextMonthDays = [self totaldaysInThisMonth:[NSDate dateWithTimeIntervalSince1970:nextMonthStamp]];
        
        formatter.dateFormat = @"dd";
        NSString *todayDay = [formatter stringFromDate:[NSDate date]];
        
        NSArray *monthDaysArray = @[@(lastMonthDays), @(thisMonthDays), @(nextMonthDays)];
        
        // 求出开始的时间戳
        NSString *startDateStr = [NSString stringWithFormat:@"%@-%@-01", yearStr[0], monthStr[0]];
        formatter.dateFormat = @"YYYY-MM";
        NSInteger startTimeStamp = [[formatter dateFromString:startDateStr] timeIntervalSince1970];
        self.startTimeStamp = startTimeStamp;
        
        NSInteger weekTemp = lastMonthFirstDayWeek;
        for (int j = 0; j < monthDaysArray.count; j++) {
            
            NSInteger datCount = [monthDaysArray[j] integerValue];
            NSInteger year = [yearStr[j] integerValue];
            NSInteger month = [monthStr[j] integerValue];
            
            NSMutableArray *section = [NSMutableArray array];
            for (int i = 0; i < datCount; i++) {
                weekTemp = weekTemp % 7;
                YAYIDateModel  *model = [[YAYIDateModel alloc] init];
                model.year = year;
                model.month = month;
                model.week = weekTemp;
                model.day = i + 1;
                
                if (j == 1 && i == [todayDay integerValue] - 1) {
                    model.isToday = YES;
                }
                
                [section addObject:model];
                weekTemp++;
            }
            [self.sectionArray addObject:section];
        }
        
    }
    return _sectionArray;
}


- (NSMutableArray *)monthParamArray
{
    if (nil == _monthParamArray) {
        _monthParamArray = [NSMutableArray array];
        
        for (int i = 0; i < self.sectionArray.count; i++) {
            YAYIDateModel *dateModel = self.sectionArray[i][0];
            // 拼接获取数据的参数，如：201605
            NSString *paramStr = [NSString stringWithFormat:@"%ld%02ld", dateModel.year, dateModel.month];
            [_monthParamArray addObject:paramStr];
        }
    }
    return _monthParamArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择日期";
    self.dataAry = [NSMutableArray array];
//    self.monthParamArray = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupTopView];
    [self createTableView];
    [self getSchedulingData:self.hospitalID];
}


-(void)setupTopView{
    
    UIView *topView = [[UIView alloc] init];
    topView.frame = CGRectMake(0, 64, SCREEN_width, 50);
    [self.view addSubview:topView];
    
    // line
    UIView *hLineView = [[UIView alloc] init];
    hLineView.backgroundColor = YAYIColor(180, 180, 180);
    [topView addSubview:hLineView];
    [hLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.bottom.mas_offset(0);
        make.width.mas_equalTo(SCREEN_width);
        make.height.mas_equalTo(0.5);
    }];
    
    CGFloat weekLblW = (SCREEN_width) / 7.0;
    CGFloat weekLblH = 50;
    NSArray *weekStrArray = @[@"一", @"二", @"三", @"四", @"五", @"六", @"日"];
    for (int i =0; i < 7; i++) {
        UILabel *weekLbl = [[UILabel alloc] init];
        weekLbl.textAlignment = NSTextAlignmentCenter;
        weekLbl.font = [UIFont systemFontOfSize:16];
        weekLbl.text = weekStrArray[i];
        weekLbl.textColor = YAYIColor(112, 108, 108);
        if (i >= 5) {
            weekLbl.textColor = [UIColor redColor];
        }
        [topView addSubview:weekLbl];
        [weekLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(i * weekLblW);
            make.top.mas_equalTo(0);
            make.height.mas_equalTo(weekLblH);
            make.width.mas_equalTo(weekLblW);
        }];
    }
}


-(void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + 50, SCREEN_width, SCREEN_height - 64 - 50)];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}


#pragma mark - 获取数据
- (void)getSchedulingData:(NSString *)hospitalID
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"wpid"] = hospitalID;
    
    // 用来保证网络接口调用了想要的次数再刷新tableview
    __block NSInteger getDataTimes = self.monthParamArray.count;
    for (int i = 0; i < self.monthParamArray.count; i++) {
        
        param[@"queryMonth"] = self.monthParamArray[i];
        YAYILog(@"param%d %@", i, param);
        
        [YAYINetWorking getWithURL:listAllWorkTime_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
            
            YAYILog(@"返回:%@", dict);
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                NSArray *dat = dict[@"data"];
                if (dat.count != 0) {
                    
                    BOOL isCurrentHos = NO;
                    for (NSDictionary *obj in dat) {
                        YAYISchededdModel *model = [[YAYISchededdModel alloc] init];
                        [model setValuesForKeysWithDictionary:obj];
                        
                        if ([obj[@"worktimeList"] count] > 0) {
                            
                            isCurrentHos = NO;
                            // 判断是不是当前医院
                            for (NSDictionary *itemDict in obj[@"worktimeList"]) {
                                
                                if ([itemDict[@"iscurrent"] isEqualToString:@"Y"]) {
                                    isCurrentHos = YES;
                                    break;
                                }
                            }
                            
                            if (isCurrentHos) {
                                // workdate转换成时间戳：workdate : 2016-06-04,
                                NSString *monthStr = [model.workdate substringWithRange:NSMakeRange(5, 2)];
                                NSString *dayStr = [model.workdate substringWithRange:NSMakeRange(8, 2)];
                                
                                YAYIDateModel *model1 = self.sectionArray[0][0];
                                NSInteger secton = [monthStr integerValue] - model1.month;
                                NSInteger subIndex = [dayStr integerValue] - 1;
                                
                                YAYIDateModel *dateModel = self.sectionArray[secton][subIndex];
                                dateModel.isSchedule = YES;
                            }
                        }
                    }
                }
                
                getDataTimes--;
                if (getDataTimes == 0) {
                    [self.tableView reloadData];
                }
            }
        }];
    }
}


#pragma mark - 工具方法
/**
 *  这个月有几天
 */
- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}


/**
 *  第一天是周几
 */
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}


/**
 *  今天是周几
 */
- (NSInteger)weekdayInToday:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    //    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}


#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYIDateCell *cell = [YAYIDateCell cellWith:tableView];
    cell.indexPath = indexPath;
    cell.delegate = self;
    
    cell.modelArray = self.sectionArray[indexPath.row];
    return cell;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sectionArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYIDateModel *model = [self.sectionArray[indexPath.row] firstObject];
    NSInteger mostCount = [self.sectionArray[indexPath.row] count] + model.week;
    NSInteger mostRowCount = mostCount / 7 + (mostCount % 7 > 0 ? 1 : 0);
    
    return mostRowCount * 35 + 40 + 10;
}


#pragma mark YAYIDateControllerDelegate
- (void)dateCellItemViewDidClickedWithIndex:(NSInteger)index indexPath:(NSIndexPath *)indexPath
{
    YAYILog(@"第%ld行的第%ld个被点击", indexPath.row, index);
    if (self.oldIndexPath) {
        YAYIDateCell *cell = [self.tableView cellForRowAtIndexPath:self.oldIndexPath];
        [cell selectItemViewAt:self.oldIndex isSelected:NO];
    }
    
    YAYIDateCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell selectItemViewAt:index isSelected:YES];
    self.oldIndexPath = indexPath;
    self.oldIndex = index;
}


@end
